package com.yf.esms.aop;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


/**
 * @author yejc
 */
@Aspect
@Component
@Slf4j
public class ControllerAop {


    @Around("@within(org.springframework.stereotype.Controller)")
    public Object aroundController(ProceedingJoinPoint pjp) throws IOException {
        return checkUserState(pjp);
    }

    @Around("@within(org.springframework.web.bind.annotation.RestController)")
    public Object aroundRestController(ProceedingJoinPoint pjp) throws IOException {
        return checkUserState(pjp);
    }

    /**
     * 校验用户的用户状态是否禁用
     * @param pjp
     * @return
     * @throws IOException
     */
    private Object checkUserState(ProceedingJoinPoint pjp) throws IOException {
        long startTime = System.currentTimeMillis();

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        Object result = null;
        try {
            result = pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        Map<String, String[]> pm = request.getParameterMap();
        long endTime = System.currentTimeMillis();
        log.info("耗时:{}ms\tURI:{}\t请求参数:{}\t最大内存:{}m\t已分配内存:{}m\t已分配内存中的剩余空间:{}m\t最大可用内存:{}m",
                (endTime - startTime), request.getRequestURI(), JSON.toJSON(pm), Runtime.getRuntime().maxMemory() / 1024 / 1024, Runtime.getRuntime().totalMemory() / 1024 / 1024, Runtime.getRuntime().freeMemory() / 1024 / 1024,
                (Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory()) / 1024 / 1024);
        return result;
    }
}
